# 页面
import os
import uuid

from django.core.cache import cache
from django.core.paginator import Paginator
from django.db.models import Q
from django.http import JsonResponse
from django.shortcuts import render
from apps.business import models
from apps.config.models import Dept_model
from apps.config.serializers import Menu_serializer
from single.settings import BASE_DIR
import datetime
import pytz
from django.db import transaction

def contract_view(request):
    # 查询操作权限
    menu_list = cache.get('menu_list')
    menu_obj = Menu_serializer(menu_list, many=True)
    return render(request, 'contract/list.html', {'data': menu_obj.data})


# 获得其数据
def contracts_list(request):
    try:
        rep_list = models.Contract_papers_model.objects.all()
        rep_count = models.Contract_papers_model.objects.count()
    except Exception as e:
        return JsonResponse({'code': 201, 'msg': '获取约定书数据失败，请联系管理员'})
    list = []
    for i in rep_list:
        # 获取当前账户的id
        ids = i.paper_dept.values_list('dept_name', 'id')
        ids_list = []
        id_list = []
        for k in ids:
            ids_list.append(k[0])
            id_list.append(k[1])
        dict = {}
        dict['id'] = i.id
        dict['paper_code'] = i.paper_code
        dict['paper_date'] = i.paper_date  # 签订时间
        dict['paper_customer'] = i.paper_customer.cus_audited_object  # 关联客户
        dict['paper_customer_id'] = i.paper_customer.id  # 关联客户id
        dict['paper_create'] = i.paper_create.username  # 起草人
        dict['paper_manager'] = i.paper_manager.username  # 项目负责人
        dict['paper_manager_id'] = i.paper_manager.id  # 项目负责人
        dict['paper_money'] = i.paper_money  # 金额
        dict['paper_type'] = i.paper_type.type_name  # 业务类型
        dict['paper_type_id'] = i.paper_type.id  # 业务类型id
        dict['paper_company'] = i.paper_company.dept_name  # 合同主体
        dict['paper_company_id'] = i.paper_company.id  # 合同主体id
        dict['paper_dept'] = ids_list  # 承做部门
        dict['paper_dept_id'] = id_list  # 承做部门
        dict['create_time'] = i.create_time.strftime("%Y-%m-%d %H:%M:%S")  # 创建时间
        dict['whether_issue'] = i.whether_issue # 是否出具报告
        dict['now_status'] = i.paper_status  # 合约状态
        dict['remark_describe'] = i.remark_describe  # 项目描述
        list.append(dict)
    pageIndex = request.GET.get('page')  # pageIndex = request.POST.get('pageIndex')
    pageSize = request.GET.get('limit')  # pageSize = request.POST.get('pageSize')
    pageInator = Paginator(list, pageSize)
    contacts = pageInator.page(pageIndex)
    res = []
    for contact in contacts:
        res.append(contact)
    Result = {'code': 0, 'mes': '成功！', 'count': rep_count, 'data': res}
    return JsonResponse(Result)


# 添加页面
def contracts_insert_view(request):
    return render(request, 'contract/insert.html')


# 约定书增加动作
@transaction.atomic
def contracts_insert(request):
    # 判断是否具有权限
    m_list = cache.get('menu_list')
    per_list = []
    for i in m_list:
        per_list.append(i.menu_code)
    if '200101' not in per_list:
        return JsonResponse({'code': 201, 'msg': '您无此权限，请联系管理员！'})
    spoint_1 = transaction.savepoint()  # 可以设置多个保存点
    customer = request.POST.get('customer')
    company = request.POST.get('company')
    is_issue = request.POST.get('is_issue')
    type_id = request.POST.get('type')
    remark = request.POST.get('remark')
    money = request.POST.get('money')
    dept_id = request.POST.get('dept')
    now_dept = list(dept_id)
    for i in now_dept:
        if i == ',':
            now_dept.remove(i)
    user = request.POST.get('user')
    reg_date = request.POST.get('date')
    # 这里采用服务器时间进行授时
    date_ins = datetime.datetime.now(pytz.timezone('PRC')).strftime("%Y%m%d")
    # 查询选中业务类型编码信息
    code_data = models.Business_type_model.objects.get(id=type_id).type_coderule_model_set.values('rule_perfix',
                                                                                                  'rule_suffix',
                                                                                                  'rule_nownum',
                                                                                                  'rule_begin',
                                                                                                  'rule_year')
    if len(code_data) == 0:
        return JsonResponse({'code': 203, 'msg': '请检查该业务类型下的编码配置！'})
    else:
        for i in code_data:
            perfix = i['rule_perfix']
            suffix = i['rule_suffix']
            nownum = i['rule_nownum']
            begin = i['rule_begin']
            year = i['rule_year']
        # 业务代码
            type_code = models.Business_type_model.objects.get(id=type_id).type_code
        # 判断起始参数（begin）跟现有参数（nownum）
            global number
            if nownum == 0:
                if suffix == 4:
                    number = '0001'
                elif suffix == 5:
                    number = '00001'
                elif suffix == 6:
                    number = '000001'
                if is_issue == 1:
                    paper_code = 'N'+str(perfix) + date_ins + type_code + number
                else:
                    paper_code = str(perfix) + date_ins + type_code + number
                try:
                    paper_obj = models.Contract_papers_model.objects.create(paper_code=paper_code, paper_date=reg_date,
                                                                         paper_customer_id=customer,
                                                                         paper_create_id=request.user.id,
                                                                         paper_manager_id=user, paper_type_id=type_id,
                                                                         paper_company_id=company, paper_money=money,
                                                                         remark_describe=remark,is_issue=is_issue
                                                                         )
                    dept_obj_list = Dept_model.objects.filter(id__in=now_dept)
                    paper_obj.paper_dept.add(*dept_obj_list)
                    # 每增加一条数据，需要对数据库nownum字段+1
                    type_obj = models.Type_coderule_model.objects.get(type_rule_id=type_id)
                    type_obj.rule_nownum = nownum + 1
                    type_obj.save()
                except Exception as e:
                    return JsonResponse({'code': 201, 'msg': '创建约定书失败，请联系管理员'})
                return JsonResponse({'code': 0, 'msg': '添加成功！'})
            else:
                num_len = len(str(nownum))
                number = ''
                if suffix == 4:
                    if num_len == 1:
                        for_str = '000'
                        number = for_str + str(nownum + 1)
                    elif num_len == 2:
                        for_str = '00'
                        number = for_str + str(nownum + 1)
                    elif num_len == 3:
                        for_str = '0'
                        number = for_str + str(nownum + 1)
                    elif num_len == 4:
                        number = str(nownum + 1)
                elif suffix == 5:
                    if num_len == 1:
                        for_str = '0000'
                        number = for_str + str(nownum + 1)
                    elif num_len == 2:
                        for_str = '000'
                        number = for_str + str(nownum + 1)
                    elif num_len == 3:
                        for_str = '00'
                        number = for_str + str(nownum + 1)
                    elif num_len == 4:
                        for_str = '0'
                        number = for_str + str(nownum + 1)
                    elif num_len == 5:
                        number = str(nownum + 1)
                elif suffix == 6:
                    if num_len == 1:
                        for_str = '00000'
                        number = for_str + str(nownum + 1)
                    elif num_len == 2:
                        for_str = '0000'
                        number = for_str + str(nownum + 1)
                    elif num_len == 3:
                        for_str = '000'
                        number = for_str + str(nownum + 1)
                    elif num_len == 4:
                        for_str = '00'
                        number = for_str + str(nownum + 1)
                    elif num_len == 5:
                        for_str = '0'
                        number = for_str + str(nownum + 1)
                    elif num_len == 6:
                        number = str(nownum + 1)
                if is_issue == 1:
                    paper_code = 'N'+str(perfix) + date_ins + type_code + number
                else:
                    paper_code = str(perfix) + date_ins + type_code + number
            try:
                paper_obj = models.Contract_papers_model.objects.create(paper_code=paper_code, paper_date=reg_date,
                                                                             paper_customer_id=customer,
                                                                             paper_create_id=request.user.id,
                                                                             paper_manager_id=user,
                                                                             paper_type_id=type_id,
                                                                             paper_company_id=company,
                                                                             paper_money=money,
                                                                             remark_describe=remark,
                                                                             is_issue=is_issue
                                                                             )
                dept_obj_list = Dept_model.objects.filter(id__in=now_dept)
                paper_obj.paper_dept.add(*dept_obj_list)
                # 每增加一条数据，需要对数据库nownum字段+1
                type_obj = models.Type_coderule_model.objects.get(type_rule_id=type_id)
                type_obj.rule_nownum = nownum + 1
                type_obj.save()
            except Exception as e:
                transaction.savepoint_rollback(spoint_1)  # 可以回滚到指定的保存点
                return JsonResponse({'code': 201, 'msg': '创建约定书失败，请联系管理员'})
            return JsonResponse({'code': 0, 'msg': '添加成功！'})


# 修改页面
def contracts_edit_view(request):
    return render(request, 'contract/edit.html')


# 修改动作
@transaction.atomic
def contracts_edit(request, id):
    # 判断是否具有权限
    m_list = cache.get('menu_list')
    per_list = []
    for i in m_list:
        per_list.append(i.menu_code)
    if '200102' not in per_list:
        return JsonResponse({'code': 201, 'msg': '您无此权限，请联系管理员！'})
    spoint_1 = transaction.savepoint()  # 可以设置多个保存点
    customer = request.POST.get('customer')  # 客户
    date = request.POST.get('date')  # 签约时间
    user = request.POST.get('user')  # 项目负责人
    type = request.POST.get('type')  # 业务类型
    money = request.POST.get('money')  # 金额
    is_issue = request.POST.get('is_issue')  # 是否出具报告
    dept = str(request.POST.get('dept')).split(',')  # 承做部门，这里可能是多个部门
    company = request.POST.get('company')  # 合同主体
    remark = request.POST.get('remark_describe')  # 备注
    try:
        dept_list = Dept_model.objects.filter(id__in=dept)
        cus_obj = models.Contract_papers_model.objects.get(pk=id)
        cus_obj.paper_customer_id = customer
        cus_obj.paper_date = date
        cus_obj.paper_manager_id = user
        cus_obj.paper_type_id = type
        cus_obj.paper_money = money
        cus_obj.paper_company_id = company
        cus_obj.remark_describe = remark
        cus_obj.paper_dept.clear()
        cus_obj.paper_dept.add(*dept_list)
        if cus_obj.whether_issue < is_issue: # 如果这里操作者现在要求出报告
            cus_obj.paper_code = 'N'+cus_obj.paper_code
            cus_obj.whether_issue = 1
        else:
            cus_obj.paper_code = cus_obj.paper_code.split('N')[1] # 如果这里操作者现在要求不出报告
            cus_obj.whether_issue = 0
        cus_obj.save()
    except Exception as e:
        transaction.savepoint_rollback(spoint_1) # 可以回滚到指定的保存点
        return JsonResponse({'code': 203, 'msg': 'contract修改模块出现问题，请联系管理员！'})
    return JsonResponse({'code': 0, 'msg': '修改成功！'})


# 查询
def con_search(request):
    name = request.GET.get('searchname')
    try:
        if len(name) == 0:
            cus_list = models.Contract_papers_model.objects.filter()
        else:
            # 支持业务类型/前缀
            cus_list = models.Contract_papers_model.objects.filter(paper_customer__cus_audited_object__contains=name)
        rep_count = len(list(cus_list))
    except Exception as e:
        print(e.args)
        return JsonResponse({'code': 201, 'msg': 'contract编码查询模块出现问题，请联系管理员！'})
    list_data = []
    for i in cus_list:
        # 获取当前账户的id
        ids = i.paper_dept.values_list('dept_name', 'id')
        ids_list = []
        id_list = []
        for k in ids:
            ids_list.append(k[0])
            id_list.append(k[1])
        dict = {}
        dict['id'] = i.id
        dict['paper_code'] = i.paper_code
        dict['paper_date'] = i.paper_date  # 签订时间
        dict['paper_customer'] = i.paper_customer.cus_audited_object  # 关联客户
        dict['paper_customer_id'] = i.paper_customer.id  # 关联客户id
        dict['paper_create'] = i.paper_create.username  # 起草人
        dict['paper_manager'] = i.paper_manager.username  # 项目负责人
        dict['paper_manager_id'] = i.paper_manager.id  # 项目负责人
        dict['paper_money'] = i.paper_money  # 金额
        dict['paper_type'] = i.paper_type.type_name  # 业务类型
        dict['paper_type_id'] = i.paper_type.id  # 业务类型id
        dict['paper_company'] = i.paper_company.dept_name  # 合同主体
        dict['paper_company_id'] = i.paper_company.id  # 合同主体id
        dict['paper_dept'] = ids_list  # 承做部门
        dict['paper_dept_id'] = id_list  # 承做部门
        dict['create_time'] = i.create_time.strftime("%Y-%m-%d %H:%M:%S")  # 创建时间
        dict['now_status'] = i.paper_status  # 合约状态
        dict['remark_describe'] = i.remark_describe  # 项目描述
        list_data.append(dict)
    pageIndex = request.GET.get('page')  # pageIndex = request.POST.get('pageIndex')
    pageSize = request.GET.get('limit')  # pageSize = request.POST.get('pageSize')
    pageInator = Paginator(list_data, pageSize)
    contacts = pageInator.page(pageIndex)
    res = []
    for contact in contacts:
        res.append(contact)
    Result = {'code': 0, 'mes': '成功！', 'count': rep_count, 'data': res}
    return JsonResponse(Result)


# 约定书附件
def confiles_view(request):
    menu_list = cache.get('menu_list')
    menu_obj = Menu_serializer(menu_list, many=True)
    return render(request, 'confiles/list.html', {'data': menu_obj.data})


# 添加页面
def confiles_insert_view(request):
    return render(request, 'confiles/insert.html')


# 查找指定状态下的能上传附件的约定书
def confiles_contracts(request):
    try:
        rep_list = models.Contract_papers_model.objects.filter(paper_status='01')
    except Exception as e:
        return JsonResponse({'code': 201, 'msg': '获取约定书数据失败，请联系管理员'})
    list = []
    for i in rep_list:
        dict = {}
        dict['id'] = i.id
        dict['paper_code'] = i.paper_code
        dict['audit_obj'] = i.paper_customer.cus_audited_object
        dict['paper_manager'] = i.paper_manager.username
        list.append(dict)
    Result = {'code': 0, 'mes': '成功！', 'data': list}
    return JsonResponse(Result)


# 上传附件
def confiles_uploads(request):
    customer_id = request.POST.get('contract_id')
    try:
        paper_code = models.Contract_papers_model.objects.get(id=customer_id).paper_code
    except Exception as e:
        return JsonResponse({'code': 201, 'msg': '数据传输失败！'})
    # 这里需要判断相关的文件夹置否存在
    if paper_code not in os.listdir("media\\papers"):
        os.chdir('media\\papers')
        os.mkdir(paper_code)
    return JsonResponse({'code': 0, 'msg': '上传成功！'})

# 附件上传
def confiles_uploads1(request):
    file_list = request.FILES.getlist('file')
    # 这里应该根据ID查找相关的
    customer_id = request.POST.get('contract_id')
    spoint_1 = transaction.savepoint()  # 可以设置多个保存点
    try:
        paper_code = models.Contract_papers_model.objects.get(id=customer_id).paper_code
        # 多对多字段是不能使用create跟save方法的
        for f in file_list:
            file_obj = models.Paper_files_model.objects.create(file_url="media\\papers\\%s\\%s" % (paper_code, f.name))
            paper_obj = models.Contract_papers_model.objects.get(paper_code=paper_code)
            files_list = models.Paper_files_model.objects.filter(id=file_obj.id)
            paper_obj.paper_file.add(*files_list)
            with open(os.path.join('%s'%('media\\papers\\%s'%paper_code),f.name),'wb') as ff:
                for chunk in f.chunks():
                    ff.write(chunk)
                ff.close()
    except Exception as e:
        transaction.savepoint_rollback(spoint_1) # 可以回滚到指定的保存点
        return JsonResponse({'code': 201, 'msg': '数据处理失败，请联系管理员！'})
    return JsonResponse({'code': 200, 'msg': '上传成功！'})

# 查询附件信息
def confiles_list(request):
    files_list=models.Paper_files_model.objects.filter()
    data_count=models.Paper_files_model.objects.count()
    data_list=[]

    for i in files_list:
        dict = {}
        dict['id'] = i.id
        dict['file_url'] = i.file_url.url
        dict['paper_contract'] = list(models.Paper_files_model.objects.get(id=i.id).contract_papers_model_set.values_list('paper_code',flat=True))
        dict['customer_name']=list(models.Paper_files_model.objects.get(id=i.id).contract_papers_model_set.values_list('paper_customer__cus_audited_object',flat=True))
        data_list.append(dict)
    pageIndex = request.GET.get('page')  # pageIndex = request.POST.get('pageIndex')
    pageSize = request.GET.get('limit')  # pageSize = request.POST.get('pageSize')
    pageInator = Paginator(data_list, pageSize)
    contacts = pageInator.page(pageIndex)
    res = []
    for contact in contacts:
        res.append(contact)
    Result = {'code': 0, 'mes': '成功！', 'count': data_count, 'data': res}
    return JsonResponse(Result)

# 删除
def confiles_del(request,id):
    # 判断是否具有权限
    m_list = cache.get('menu_list')
    per_list = []
    for i in m_list:
        per_list.append(i.menu_code)
    if '200203' not in per_list:
        return JsonResponse({'code': 201, 'msg': '您无此权限，请联系管理员！'})
    spoint_1 = transaction.savepoint()  # 可以设置多个保存点
    try:
        file_url=models.Paper_files_model.objects.get(pk=id).file_url.url
        os.remove(file_url)
        models.Paper_files_model.objects.get(pk=id).delete()
    except Exception as e:
        transaction.savepoint_rollback(spoint_1)  # 可以回滚到指定的保存点
        return JsonResponse({'code': 201, 'msg': '数据删除失败，请联系管理员！'})
    return JsonResponse({'code':0,'msg':'删除成功！'})

# 查询
def confiles_search(request):
    name = request.GET.get('searchname')
    cus_list =''
    global count
    try:
        if len(name) == 0:
            cus_list = models.Paper_files_model.objects.filter()
            count = models.Paper_files_model.objects.filter().count()
        else:
            # 支持客户代码/约定书代码查询
            paper_data=models.Contract_papers_model.objects.filter(Q(paper_customer__cus_audited_object__contains=name)|Q(paper_code__contains=name))
            for i in paper_data:
                # cus_list = models.Paper_files_model.objects.filter(customers_papers_model__paper_file=i.id)
                count = models.Paper_files_model.objects.filter(pk=i.id).count()
                files_data = list(i.paper_file.values_list('id',flat=True))
                cus_list = models.Paper_files_model.objects.filter(id__in=files_data)
                count = models.Paper_files_model.objects.filter(id__in=files_data).count()
    except Exception as e:
        print(e.args)
        return JsonResponse({'code': 201, 'msg': '约定书附件模块查询出现问题，请联系管理员！'})
    list1 = []
    for i in cus_list:
        dict = {}
        dict['id'] = i.id
        dict['file_url'] = i.file_url.url
        dict['paper_contract'] = list(models.Paper_files_model.objects.get(id=i.id).customers_papers_model_set.values_list('paper_code',flat=True))
        dict['customer_name'] =list(models.Paper_files_model.objects.get(id=i.id).customers_papers_model_set.values_list('paper_customer__cus_audited_object',flat=True))
        list1.append(dict)
    pageIndex = request.GET.get('page')  # pageIndex = request.POST.get('pageIndex')
    pageSize = request.GET.get('limit')  # pageSize = request.POST.get('pageSize')
    pageInator = Paginator(list1, pageSize)
    contacts = pageInator.page(pageIndex)
    res = []
    for contact in contacts:
        res.append(contact)
    return JsonResponse({'code': 0, 'msg': '成功！', 'count': count, 'data': res})